import { computed, reactive, ref } from 'vue'
import apis, { request } from '../apis/index.js'
import itf from '../utils/interface.js'
import { envs, env, context } from '../configs/index.js'
import { debug } from 'console'

export default function useLogin() {
  const miniProgramAppid = 'wxb46413b25164110a'
  const appAppid = 'wxc7dd86cfd9983e9a'

  /* 手机号码 */
  function validatePhoneNumber(str) {
    const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    return reg.test(str)
  }

  /* 企业名称 */
  function validateEnterName(str) {
    const reg =
      /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_.()（）。&]){1,100}$/
    return reg.test(str)
  }

  /* 联系人名称 */
  function validateContacts(str) {
    const reg = /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z]){1,100}$/
    return reg.test(str)
  }

  function getEntrance(entrance) {
    if (env === envs.test) {
      if (entrance === 'Before') {
        return 'saas-testing_loginBefore'
      } else {
        return 'saas-testing_loginAfter'
      }
    } else if (env === envs.prod) {
      if (entrance === 'Before') {
        return 'saas-prod_loginBefore'
      } else {
        return 'saas-prod_loginAfter'
      }
    }
  }

  const tempCode = ref({}) //临时用
  //wechat登录
  function wxLogin(entrance) {
    /* #ifdef  APP-PLUS */
    let appLogin = weixinLogin(entrance)

    /* #endif */

    /* #ifdef  MP-WEIXIN */

    let userInfo = getUserInfo()
    let wxCode = getLogin()

    Promise.all([userInfo, wxCode])
      .then((res) => {
        //都获取权限成功
        let loginRes = res[1]
        const { code } = loginRes
        getUnionId(code, false, entrance, miniProgramAppid)
      })
      .catch((err) => {
        console.log('---Promise.all--catch err---', err)
      })

    /* #endif */
  }

  /** @function 选择租户并生成token */
  async function getUnionId(code, flag = false, entrance, appId) {
    try {
      const params = { code: code, appId: appId }

      // 请求配置
      const optionalConfig = {
        disableToken: true,
        specialHeader: {
          'Req-Place': 'AppLogin',
        },
      }

      const token = await request.get(
        apis.getPublicAccountUnionId,
        params,
        optionalConfig
      )

      itf.setStorageSync('openId', token.openid)

      if (!flag) {
        getUserStateByUnionId(token.unionid, entrance)
      }
    } catch (e) {
      console.log(e.message)
    }
  }

  /** @function 查询登录状态和绑定关系   entrance 入口*/
  async function getUserStateByUnionId(code, entrance) {
    const entry = getEntrance(entrance)
    const params = { unionId: code, loginPlaceName: 'AppLogin', state: entry }

    // 请求配置
    const optionalConfig = {
      disableToken: true,
      specialHeader: {
        'Req-Place': 'AppLogin',
      },
    }

    const token = await request.get(
      apis.getUserStateByUnionId,
      params,
      optionalConfig
    )

    const { state, choiceTenant } = token

    if ('binding' === state) {
      //已绑定
      // 只有一个租户身份时自动选择
      doSelectTenant(choiceTenant)
      // if (choiceTenant.length) {
      // 	loadTenantPrepare(choiceTenant[0])
      // }
    } else {
      //未绑定，跳转
      itf.navigateTo({
        url: '/pages/auth/register/bindReg',
      })
    }
  }

  /** @function 校验手机验证码是否正确 */
  async function checkVerificationCode({
    username,
    code,
    enterpriseName,
    contacts,
  }) {
    try {
      if (!validateEnterName(enterpriseName)) {
        itf.showToast({
          title: '企业名称不能包含特殊符号！',
        })
        return
      }

      if (!validateContacts(contacts)) {
        itf.showToast({
          title: '联系人名称仅支持汉字、字母！',
        })
        return
      }

      // itf.showLoading({
      // 	title: '正在绑定',
      // })

      // 登录参数
      const params = {
        phoneNum: username,
        verifiedCode: code,
        smsType: 'Register',
      }

      // 请求配置
      const optionalConfig = {
        disableToken: true,
        specialHeader: {
          'Req-Place': 'AppLogin',
        },
      }

      const req = await request.post(
        apis.checkVerificationCode,
        params,
        optionalConfig
      )

      //校验通过

      bingding({ username, code, enterpriseName, contacts })

      // bingding
    } catch (err) {
      throw new Error(err.message)
    } finally {
      // itf.hideLoading()
    }
  }

  /** @function 注册绑定 */
  async function bingding({ username, code, enterpriseName, contacts }) {
    if (!validateEnterName(enterpriseName)) {
      itf.showToast({
        title: '企业名称不能包含特殊符号！',
      })
      return
    }

    if (!validateContacts(contacts)) {
      itf.showToast({
        title: '联系人名称仅支持汉字、字母！',
      })
      return
    }

    try {
      // itf.showLoading({
      // 	title: '正在注册',
      // })

      // 登录参数
      const params = {
        checkAgreementFlag: true,
        mobile: username,
        loginType: 'verifyCode',
        shortMessageVerifiedCode: code,
        enterpriseName,
        contacts,
        buildControls: 'ignoreCheckRegisterDTO',
      }

      // 请求配置
      const optionalConfig = {
        disableToken: true,
        specialHeader: {
          'Req-Place': 'AppLogin',
        },
      }

      const availableTenantList = await request.post(
        apis.register,
        params,
        optionalConfig
      )

      // 只有一个租户身份时自动选择
      if (availableTenantList.length) {
        const firstTenant = availableTenantList[0]

        itf.navigateTo({
          url: `/pages/auth/register/result?tenant=${encodeURIComponent(
            JSON.stringify(firstTenant)
          )}&username=${username}`,
        })
      }
    } catch (err) {
      throw new Error(err.message)
    } finally {
      // itf.hideLoading()
    }
  }

  function doSelectTenant(tenantList, username, password) {
    // 只有一个租户身份时自动选择
    if (tenantList.length > 1) {
      //选择租户
      itf.navigateTo({
        url: `/pages/auth/choiceTenant/index?tenant=${encodeURIComponent(
          JSON.stringify(tenantList)
        )}&username=${username}&password=${password}`,
      })
    } else if (tenantList.length === 1) {
      if (['APT', 'PT', 'SCT'].includes(tenantList[0].appVersion)) {
        tempCode.value = { code: '-2' }
        return { code: '-2' }
      }

      //直接进入
      loadTenantPrepare(tenantList[0], username, password)
    }
  }

  function loadTenantPrepare(tenants, username, password) {
    switch (tenants.tenantState) {
      case 'enable':
      case 'stop':
        loadTenant({
          id: tenants.id,
          name: tenants.tenantName,
          username,
          password,
        })
        break
      case 'init':
        itf.showToast({
          title: '当前租户正在初始化，请稍后再登录',
        })
        break
      case 'fail':
        itf.showToast({
          title: '当前租户初始化失败，请联系管理员',
        })
        break
      default:
        break
    }
  }

  /** @function 选择租户并生成token */
  async function loadTenant({ id, name, username, password }) {
    const params = { tenantId: id }

    // 请求配置
    const optionalConfig = {
      disableToken: true,
      specialHeader: {
        'Req-Place': 'AppLogin',
      },
    }

    const token = await request.post(
      apis.loadTenantInfo,
      params,
      optionalConfig
    )

    itf.setStorageSync('tenant', name)
    itf.setStorageSync('token', token)
    itf.setStorageSync('username', username)

    const today = new Date()
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const expiryTime = new Date(
      `${tomorrow.getFullYear()}/${
        tomorrow.getMonth() + 1
      }/${tomorrow.getDate()}`
    ).getTime()
    itf.setStorageSync('password', {
      value: password,
      expiry: expiryTime,
    })

    itf.redirectTo({
      url: '/pages/home/index',
    })
  }

  /** @function 查找状态 */
  async function findTenantInfoByUser({ username }) {
    const params = { mobile: username }

    // 请求配置
    const optionalConfig = {
      disableToken: true,
      specialHeader: {
        'Req-Place': 'AppLogin',
      },
    }

    try {
      const data = await request.post(
        apis.findTenantInfoByUser,
        params,
        optionalConfig
      )

      if (data.tenantState === 'enable') {
        saasHome({ tenantId: data.id }).then((res) => {
          setTimeout(() => {
            parent.document.getElementById('odd').click()
            clearInterval(this.initTimeId)
            this.initTimeId = null
          }, 300)
        })
      } else if (data.tenantState === 'fail') {
        this.tenantName = data.tenantName

        this.watiSrc = waitFailed
        this.dialog = true
        this.dialogSuccess = false
        clearInterval(this.initTimeId)
        this.initTimeId = null
      }
    } catch (err) {
      throw new Error(err.message)
    } finally {
      itf.hideLoading()
      isLoading.value = false
    }
  }

  function getUserInfo() {
    return new Promise((resolve, reject) => {
      uni.getUserProfile({
        lang: 'zh_CN',
        desc: '用户登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，
        success: (res) => {
          resolve(res.userInfo)
        },
        fail: (err) => {
          reject(err)
        },
      })
    })
  }

  function getLogin() {
    return new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        onlyAuthorize: true, // 微信登录仅请求授权认证
        success(res) {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        },
      })
    })
  }

  function weixinLogin(entrance) {
    uni.getProvider({
      service: 'oauth',
      success: function (res) {
        //支持微信、qq和微博等
        if (~res.provider.indexOf('weixin')) {
          uni.login({
            provider: 'weixin',
            onlyAuthorize: true, // 微信登录仅请求授权认证
            success: function (event) {
              // loginRes.authResult
              const { code } = event
              getUnionId(code, false, entrance, appAppid)
            },
            fail: function (err) {
              if (err.code === -8) {
                itf.showToast({
                  title: '微信客户端未安装',
                })
              }
            },
          })
        }
      },
      fail: function (err) {
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: err,
        })
      },
    })
  }

  return reactive({
    miniProgramAppid,
    appAppid,
    validatePhoneNumber,
    getUserInfo,
    getLogin,
    weixinLogin,
    loadTenantPrepare,
    bingding,
    getUnionId,
    wxLogin,
    doSelectTenant,
    checkVerificationCode,
    tempCode,
  })
}
